import { defineStore } from 'pinia'
import axios from 'axios'
import { useCookies } from 'vue3-cookies'

const { cookies } = useCookies()
const API_URL = import.meta.env.VITE_API_URL || 'http://localhost:8000'

// 创建用于认证的axios实例
const authAxios = axios.create({
  baseURL: API_URL,
  timeout: 10000,
  headers: {
    'Accept': 'application/json'
  },
  withCredentials: true // 确保跨域请求发送cookies
})

export const useAuthStore = defineStore('auth', {
  state: () => ({
    user: null as any,
    token: cookies.get('auth_token') || null as string | null,
    isLoading: false,
    error: null as string | null
  }),
  
  getters: {
    isAuthenticated: (state) => !!state.token,
    currentUser: (state) => state.user,
  },
  
  actions: {
    async login(username: string, password: string) {
      this.isLoading = true
      this.error = null
      
      try {
        const response = await authAxios.post('/api/auth/login/', {
          username,
          password
        })
        
        this.token = response.data.key || 'session-auth'
        cookies.set('auth_token', this.token as string, '1d')
        
        // 获取用户信息
        await this.fetchUserInfo()
        return true
      } catch (error: any) {
        console.error('Login error:', error)
        this.error = error.response?.data?.non_field_errors?.[0] || '登录失败，请检查您的凭据'
        return false
      } finally {
        this.isLoading = false
      }
    },
    
    async fetchUserInfo() {
      if (!this.token) return
      
      try {
        const response = await authAxios.get(`/api/auth/user/`)
        this.user = response.data
      } catch (error) {
        console.error('Error fetching user info:', error)
        this.logout()
      }
    },
    
    logout() {
      this.user = null
      this.token = null
      cookies.remove('auth_token')
    },
    
    async register(userData: any) {
      this.isLoading = true
      this.error = null
      
      try {
        await authAxios.post(`/api/auth/register/`, userData, {
          headers: {
            'Content-Type': 'application/json'
          }
        })
        // 注册成功后自动登录
        await this.login(userData.username, userData.password)
        return true
      } catch (error: any) {
        console.error('Registration error:', error)
        this.error = error.response?.data?.detail || '注册失败，请稍后再试'
        return false
      } finally {
        this.isLoading = false
      }
    }
  }
}) 